﻿using System;
using System.Windows;
using System.Text.RegularExpressions;

namespace Silverlight.InputCtrl
{
    public class RegExpresisonValidator: ValidatorBase
    {
        private Regex Regexpression
        {
            get { return (Regex)GetValue(RegexpressionProperty); }
            set { SetValue(RegexpressionProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Regexpression.  This enables animation, styling, binding, etc...
        private static readonly DependencyProperty RegexpressionProperty =
            DependencyProperty.Register("Regexpression", typeof(Regex), typeof(RegExpresisonValidator), new PropertyMetadata(null));

        public string Expression
        {
            get { return (string)GetValue(ExpressionProperty); }
            set { SetValue(ExpressionProperty, value); }
        }
        // Using a DependencyProperty as the backing store for Expression.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ExpressionProperty =
            DependencyProperty.Register("Expression", typeof(string), typeof(RegExpresisonValidator), new PropertyMetadata(ExpressionPropertyChangedCallback));

        private static void ExpressionPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                d.SetValue(RegexpressionProperty,
                    new Regex((string)e.NewValue));
            }
            catch
            {
                d.SetValue(RegexpressionProperty, null);
            }
        }

        public override bool Validate()
        {
            base.IsValidResult = true;
            FrameworkElement _elemValidate = base.ElementValidator;
            if (_elemValidate != null && Enabled)
            {
                string value = "";
                value = ValidatorCommon.GetValueText(_elemValidate,base.PropertyToValidate);
                if (!String.IsNullOrEmpty(value))
                {
                    value = value.Trim();
                    base.IsValidResult = false;
                    if (Regexpression != null)
                    {
                        base.IsValidResult = Regexpression.IsMatch(value);                
                    }
                }
            }
            return base.IsValidResult;
        }
    }
}
